<template>
  <div class="navbar">
    <div class="navbar-container">
      <!-- Logo -->
      <div class="logo" @click="goHome">
        <h1>纪念品商城</h1>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品"
          class="search-input"
          clearable
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <!-- 右侧菜单 -->
      <div class="nav-menu">
        <el-button text @click="goToAnnouncement">
          <el-icon :size="20"><Bell /></el-icon>
          公告
        </el-button>
        <el-button text @click="goToCouponCenter">
          <el-icon :size="20"><Ticket /></el-icon>
          领券
        </el-button>
        <el-button text @click="goToCart">
          <el-icon :size="20"><ShoppingCart /></el-icon>
          购物车
        </el-button>
        <el-button text @click="goToOrders">
          <el-icon :size="20"><List /></el-icon>
          我的订单
        </el-button>
        <el-dropdown v-if="isLoggedIn" trigger="click" @command="handleUserCommand">
          <div class="user-info">
            <img :src="getUserAvatar()" class="user-avatar" />
            <span class="user-name">{{ getUserName() }}</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="myCollects">
                <el-icon><Star /></el-icon>
                我的收藏
              </el-dropdown-item>
              <el-dropdown-item command="myCoupons">
                <el-icon><Ticket /></el-icon>
                我的优惠券
              </el-dropdown-item>
              <el-dropdown-item command="changePassword">
                <el-icon><Lock /></el-icon>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button v-else text @click="userStore.openLoginDialog()">
          <el-icon :size="20"><User /></el-icon>
          登录
        </el-button>
      </div>
    </div>
    
    <!-- 修改密码对话框 -->
    <ChangePasswordDialog v-model="showChangePasswordDialog" @success="handlePasswordChanged" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getFileUrl } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ShoppingCart, List, User, Bell, ArrowDown, Lock, SwitchButton, Ticket, Star } from '@element-plus/icons-vue'
import ChangePasswordDialog from './ChangePasswordDialog.vue'

const router = useRouter()
const userStore = useUserStore()
const searchKeyword = ref('')
const showChangePasswordDialog = ref(false)

// 是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn())

// 获取用户名
const getUserName = () => {
  return userStore.userInfo?.name || '用户'
}

// 获取用户头像
const getUserAvatar = () => {
  const avatar = userStore.userInfo?.avatar
  if (!avatar) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
  return getFileUrl(avatar)
}

// 组件挂载时，如果已登录但没有用户信息，则获取
onMounted(async () => {
  if (userStore.isLoggedIn() && !userStore.userInfo) {
    try {
      await userStore.getUserInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
})

const goHome = () => {
  router.push('/')
}

const handleSearch = () => {
  const keyword = searchKeyword.value.trim()
  if (keyword) {
    // 跳转到搜索结果页
    router.push({
      path: '/search',
      query: { keyword }
    })
    // 清空搜索框（可选）
    // searchKeyword.value = ''
  } else {
    ElMessage.warning('请输入搜索关键词')
  }
}

const goToAnnouncement = () => {
  router.push('/announcement')
}

const goToCouponCenter = () => {
  router.push('/coupon-center')
}

const goToCart = () => {
  if (!isLoggedIn.value) {
    userStore.openLoginDialog()
    return
  }
  router.push('/cart')
}

const goToOrders = () => {
  if (!isLoggedIn.value) {
    userStore.openLoginDialog()
    return
  }
  router.push('/my-orders')
}

const goToProfile = () => {
  if (!isLoggedIn.value) {
    userStore.openLoginDialog()
    return
  }
  router.push('/profile')
}

// 处理用户菜单命令
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      goToProfile()
      break
    case 'myCollects':
      router.push('/my-collects')
      break
    case 'myCoupons':
      router.push('/my-coupons')
      break
    case 'changePassword':
      showChangePasswordDialog.value = true
      break
    case 'logout':
      await handleLogout()
      break
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    userStore.logout()
    ElMessage.success('已退出登录')
    
    // 如果当前在个人中心页面，跳转到首页
    if (router.currentRoute.value.path === '/profile') {
      router.push('/')
    }
  } catch {
    // 取消退出
  }
}

// 修改密码成功
const handlePasswordChanged = () => {
  ElMessage.success('密码修改成功，请重新登录')
  // 退出登录
  userStore.logout()
  // 打开登录对话框
  userStore.openLoginDialog()
}
</script>

<style scoped>
.navbar {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  height: 70px;
  display: flex;
  align-items: center;
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 30px;
}

.logo {
  cursor: pointer;
  user-select: none;
}

.logo h1 {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
  margin: 0;
  white-space: nowrap;
}

.search-box {
  flex: 1;
  max-width: 600px;
}

.search-input {
  width: 100%;
}

.nav-menu {
  display: flex;
  gap: 10px;
  align-items: center;
}

.nav-menu .el-button {
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .navbar-container {
    flex-wrap: wrap;
    gap: 10px;
  }

  .logo h1 {
    font-size: 18px;
  }

  .search-box {
    order: 3;
    flex: 1 1 100%;
  }

  .nav-menu {
    gap: 5px;
  }

  .nav-menu .el-button {
    font-size: 12px;
    padding: 8px;
  }
}
</style>
